/* eslint-disable multiline-ternary */
/*
 * @Author       : wfl
 * @LastEditors: ww
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-08 12:19:42
 * @LastEditTime: 2023-06-02 09:55:49
 */
import { ElButton, ElSkeleton, ElSwitch } from 'element-plus'
import { ikTree } from 'iking-utils'
import { Suspense, type Ref } from 'vue'
import { useClipboard } from '@vueuse/core'
import useRouteStore from '@g/store/modules/route'
import IkPageFull from '@g/components/LayoutCom/IkPageFull/index.vue'
import IkPageMain from '@g/components/LayoutCom/IkPageMain/index.vue'
import SortModal from './MenuSortModal.vue'
import MenuModal from './MenuEditModal.vue'
import { useFields } from './fields'
import IkBtnContent from '@/global/components/BaseCom/IkBtnContent'
import IkSvgIcon from '@/global/components/BaseCom/IkSvgIcon/index.vue'
import menuApi from '@/MainApp/apis/menu'
import { MenuBtnEnum } from '@/global/enums/menu'
import './menu.scss'

const menuManage = defineComponent({
  components: {
    MenuModal
  },
  setup() {
    const { copy } = useClipboard({ legacy: true })
    const { t } = useConfig()
    // const { loadUrl } = useHttpUrl()
    const { msgSuccess, msgError, msgBoxWarnAsync } = useMessage()
    const routeStore = useRouteStore()

    const { fieldList } = useFields()

    const loading = ref(false)
    const isChild = ref(false)
    // const moving = ref(false)
    const menuTree: Ref<null | Array<any>> = ref(null)
    const defaultExpand: Ref<string[]> = ref([])
    const sortModalVisible = ref(false)
    const router = useRouter()
    const refreshRoute = () => {
      // 不需要动态更新菜单列表时，注释下面这行代码
      routeStore.generateRoutesAtBack()
      // TODO 修改菜单渲染逻辑
      // routeStore.flatRoutes?.forEach(route: RouteRecordRaw => {
      //   if (!/^(https?:|mailto:|tel:)/.test(route.path) && !router.hasRoute(route.name))
      //     router.addRoute(route)
      // })
    }

    // 获取菜单数据
    const getMenuTreeData = (statu = false) => {
      // 排序时DOM结构被更改，此操作用于正确显示排序后的结果
      if (statu)
        menuTree.value = []

      loading.value = true
      menuApi
        .getUserMenuList(true)
        .then(({ success, data, msg }) => {
          if (success) {
            menuTree.value = ikTree.listToTree(
              data.map(
                (item: { key: string; loading: Boolean; }, index: number) => {
                  item.key = `${index}`
                  item.loading = false
                  return item
                }
              )
            )
            defaultExpand.value
              = menuTree.value?.map((item: { key: string; }) => item.key) || []
          }
          else {
            msgError(msg)
          }

          loading.value = false
        })
        .catch(() => {
          loading.value = false
          menuTree.value = []
        })
    }
    getMenuTreeData()

    // 新增、修改、编辑
    const visible = ref(false)
    const editData = ref(null)
    // 新增菜单
    const handleNewMenu = () => {
      editData.value = null
      isChild.value = false
      visible.value = true
    }
    // 修改显示状态
    const handChangeStatu = async (row: {
      visible: Boolean
      loading: Boolean
    }) => {
      row.loading = true
      const { msg, success } = await menuApi.updateMenu(row)
      if (success) {
        msgSuccess(msg)
        refreshRoute()
      }
      else {
        msgError(msg)
        // 修改失败 回退状态
        row.visible = !row.visible
      }
      row.loading = false
    }
    // 修改
    const handEditRow = (row: any) => {
      editData.value = row
      visible.value = true
      isChild.value = false
    }
    // 新增子菜单
    const handAddChild = (row: any) => {
      editData.value = row
      isChild.value = true
      visible.value = true
    }

    // 删除
    const handDeleteMenu = (row: any) => {
      let str = ''
      if (row.menuType === MenuBtnEnum.MENU)
        str = `删除后，菜单【${row.name}】及其所有的子菜单、按钮将被全部删除，无法恢复。确定删除吗？`
      else
        str = `确定删除按钮【${row.name}】吗？`
      msgBoxWarnAsync('确认删除', str, async () => {
        const { success, msg } = await menuApi.deleteMenu(row.id)
        if (success) {
          getMenuTreeData()
          // 菜单更改成功，重新渲染
          routeStore.generateRoutesAtBack()
        }
        else { msgError(msg) }
      })
    }
    const handSort = () => {
      sortModalVisible.value = true
    }
    const sortModalCancel = () => {
      sortModalVisible.value = false
      // 菜单更改成功，重新渲染
      routeStore.generateRoutesAtBack()
    }

    // 复制权限码
    const handCopyCode = (code: string) => {
      copy(code)
    }
    return () => (
      <>
        <Suspense>
         <IkPageFull
                header-title="菜单列表"
                table-data={menuTree.value || []}
                fields={fieldList.value}
                loading={loading.value}
                row-key="id"
                serial={false}
                search={() => getMenuTreeData()}
                expand-row-keys={defaultExpand.value} >
                {{
                  headerRight: () => <>
                    <ElButton type="primary" v-role="$ADD-MENU" onClick={() => handleNewMenu()}></ElButton>
                    <IkSvgIcon
                      v-role="SORT-MENU"
                      size="big"
                      show-bg
                      pop
                      title={t('action.sort')}
                      name="iksvg_hanggao"
                      onClick={() => handSort()}
                    />
                  </>,
                  icon: ({ data }: { data: any; }) => <IkSvgIcon name={data.row.icon} />,
                  visible: ({ data }: { data: any; }) =>
                    <ElSwitch
                      v-model={data.row.visible}
                      loading={data.row.loading as any}
                      onChange={() => handChangeStatu(data.row)}
                      inline-prompt
                    />,
                  permissionCode: ({ data }: { data: any; }) => <>
                    <span onClick={() => handCopyCode(data.row.permissionCode)}>{data.row.permissionCode || ''}</span>
                  </>,
                  operate: ({ data }: { data: any; }) => data.row.menuType === MenuBtnEnum.PAGE_BUTTON ? (
                    <IkBtnContent>
                      <IkSvgIcon
                        v-role="UPDATE-MENU"
                        show-bg
                        start-margin={false}
                        name="icon-bianji"
                        pop
                        in-table
                        title={t('action.modify')}
                        onClick={() => handEditRow(data.row)}
                      />
                      <IkSvgIcon
                        v-role="DELETE-MENU"
                        show-bg
                        pop
                        in-table
                        name="icon-shanchu"
                        title={t('action.delete')}
                        type="danger"
                        onClick={() => handDeleteMenu(data.row)}
                      />
                    </IkBtnContent>
                  ) : (
                    <IkBtnContent num={3}>
                      <IkSvgIcon
                        v-role="ADD-CHILD-MENU"
                          show-bg
                          pop
                          in-table
                        name="iksvg_xinzeng"
                        start-margin={false}
                        title={t('action.addchild')}
                        onClick={() => handAddChild(data.row)}
                      />
                      <IkSvgIcon
                        v-role="UPDATE-MENU"
                          show-bg
                          pop
                          in-table
                          name="iksvg_bianji"
                          title={t('action.modify')}
                        onClick={() => handEditRow(data.row)}
                      />
                      <IkSvgIcon
                        v-role="DELETE-MENU"
                          show-bg
                          pop
                          in-table
                          name="iksvg_shanchu"
                          type="danger"
                        title={t('action.delete')}
                        onClick={() => handDeleteMenu(data.row)}
                      />
                    </IkBtnContent>
                  )
                }}
          </IkPageFull>
        </Suspense>
          <MenuModal
             isChild={isChild.value}
                editData={editData.value}
                v-model={visible.value}
                onUpdateData={() => {
                  editData.value = null
                  visible.value = false
                  getMenuTreeData()
              }}
          />
          <SortModal
             v-model:visible={sortModalVisible.value}
                menuTree={menuTree.value || []}
                onConfirm={() => {
                  sortModalVisible.value = false
                  getMenuTreeData()
                }}
             onCancel={() => sortModalCancel()}
          />
     </>

    )
  }
})

export default menuManage
